package com.lee.adapter.controller;

import com.lee.adapter.service.HandlerAdapter;
import com.lee.adapter.service.impl.RequestMappingHandlerAdapter;
import com.lee.adapter.service.impl.SimpleHandlerAdapter;
import com.lee.adapter.service.impl.SimpleServletHandlerAdapter;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zfl_a
 * @Desc 入口测试
 * @date 2020/8/16
 * @project springboot_design_pattern
 */
@RestController
public class DispatcherController implements InitializingBean {

    //自动装配
    @Autowired
    private Map<String,Controller> controllerMap = new HashMap<>();

    private List<HandlerAdapter> handlerAdapters = new ArrayList<>();

    /**
     * 处理
     * @param controllerName simpleController simpleServletController httpRequestController
     * @return
     */
    @GetMapping("/doService")
    public String doService(String controllerName){

        return doDispatcher(controllerName);
    }

    private String doDispatcher(String controllerName) {

        // 获取适配器 参数可根据具体的Handler替换
        Controller controller = controllerMap.get(controllerName);
        HandlerAdapter ha = getHandlerAdapter(controller);
        if(ha == null) {
            return "没有此适配器";
        }
        //具体处理
        return ha.handle(controller);
    }

    /**
     * 获取适配器
     * @param controller
     * @return
     */
    private HandlerAdapter getHandlerAdapter(Controller controller) {
        if (this.handlerAdapters != null) {
            for (HandlerAdapter ha : this.handlerAdapters) {
                if (ha.supports(controller)) {
                    return ha;
                }
            }
        }
        return null ;
    }

    @Override
    public void afterPropertiesSet() throws Exception {

        //初始化适配器实例
        RequestMappingHandlerAdapter mappingHandlerAdapter = new RequestMappingHandlerAdapter();
        SimpleHandlerAdapter simpleHandlerAdapter = new SimpleHandlerAdapter();
        SimpleServletHandlerAdapter servletHandlerAdapter = new SimpleServletHandlerAdapter();
        handlerAdapters.add(mappingHandlerAdapter);
        handlerAdapters.add(simpleHandlerAdapter);
        handlerAdapters.add(servletHandlerAdapter);
    }
}
